<template>
    <div>
        <!--面包屑导航区域-->
        <el-breadcrumb separator="/">
            <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>题库管理</el-breadcrumb-item>
            <el-breadcrumb-item>题库列表</el-breadcrumb-item>
        </el-breadcrumb>

         <!--卡片视图区域-->
        <el-card>
            <el-row :gutter="20">
                <el-col :span=8>
                    <el-input placeholder="请输入内容" v-model="queryInfo.query" clearable @clear="getGoodsList">
                        <el-button slot="append" icon="el-icon-search" @click="getGoodsList"></el-button>
                    </el-input>
                </el-col>
                <el-col :span=4>
                    <el-button type="primary" @click="addDialogVisible = true">添加题目</el-button>
                </el-col>
              <el-col :span="4">
                <el-button type="success" @click="importDialogVisible = true">批量导入题目</el-button>
                <!--                此处存疑-->
              </el-col>
            </el-row>

            <!--table表格区域-->
          <el-collapse v-model="num" @change="handleChange">
            <el-collapse-item v-for="(item,index) in showQuestionList" v-bind:key="index" :title=item.title :name=index>
              <div v-if="item.option1 !==''">A.{{item.option1}}</div>
              <div v-if="item.option2 !==''">B.{{item.option2}}</div>
              <div v-if="item.option3 !==''">C.{{item.option3}}</div>
              <div v-if="item.option4 !==''">D.{{item.option4}}</div>
              <div v-if="item.answ !== ''">答案：{{item.answ}}</div>
              <div>创建人:{{item.uid}}</div>
              <div>题目id:{{item.qid}}</div>
            </el-collapse-item>
          </el-collapse>

            <!--分页区域-->
             <el-pagination
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page="queryInfo.pagenum"
                :page-sizes="[1,2,5,10,15]"
                :page-size="queryInfo.pagesize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="total" background>
            </el-pagination>
        </el-card>

      <!--批量导入对话框!-->
      <el-dialog title="批量导入题目"  :visible.sync="importDialogVisible"
                 width="30%">
<!--                 @close="importDialogClosed">-->
        <el-upload
          ref="upload"
          action="/"
          :on-change="importExcel"
          accept=".xlsx, .xls"
          :show-file-list="false"
          :auto-upload="false">
          <el-button size="small" type="primary">上传题目</el-button>
          <div slot="tip" class="el-upload__tip">只能上传xls、xlsx文件，且不超过500kb</div>
        </el-upload>
      </el-dialog>

      <!--添加用户的对话框-->
      <el-dialog
        title="添加问题"
        :visible.sync="addDialogVisible"
        width="30%"
        @close="addDialogClosed">
        <!--内容主体区域-->
        <el-form :model="addForm" :rules="addFormRules" ref="addFormRef"  label-width="70px">
          <el-form-item label="问题" prop="title">
            <el-input v-model="addForm.title"></el-input>
          </el-form-item>
<!--          <el-form-item label="类型" prop="type">-->
<!--            <el-input v-model="addForm.type"></el-input>-->
<!--          </el-form-item>-->
          <el-form-item label="问题类型">
            <el-select v-model="value" placeholder="请选择">
              <el-option
                v-for="item in options"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="选项个数" v-if="value === 'selection'">
            <el-input-number v-model="chooseNum"  :min="1" :max="4" label="选项个数"></el-input-number>
          </el-form-item>
          <div v-if="value === 'selection'">
            <el-form-item label="选项一" prop="option1">
              <el-input v-model="addForm.option1"></el-input>
            </el-form-item>
            <el-form-item v-if="chooseNum >= 2" label="选项二" prop="option2">
              <el-input v-model="addForm.option2"></el-input>
            </el-form-item>
            <el-form-item v-if="chooseNum >= 3"  label="选项三" prop="option3">
              <el-input v-model="addForm.option3"></el-input>
            </el-form-item>
            <el-form-item v-if="chooseNum === 4"  label="选项四" prop="option4">
              <el-input v-model="addForm.option4"></el-input>
            </el-form-item>
          </div>
        </el-form>
        <!--底部区域-->
        <span slot="footer" class="dialog-footer">
                <el-button @click="addDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="addQues">确 定</el-button>
        </span>
      </el-dialog>
    </div>
</template>

<script>
// import * as XLSX from 'xlsx'
import * as XLSX from 'xlsx/xlsx.mjs'
/* load 'fs' for readFile and writeFile support */
import * as fs from 'fs'
XLSX.set_fs(fs)
export default {
    data () {
        return {
          chooseNum: 1,
          options: [{
            value: 'selection',
            label: '选择题'
          }, {
            value: 'description',
            label: '填写题'
          }],
          value: 'selection',
            // 查询参数对象
            queryInfo: {
                query: '',
                pagenum: 1,
                pagesize: 10
            },
          addForm: {
            qid: '',
            uid: '',
            title: '',
            type: 'selection',
            answ: '',
            option1: '',
            option2: '',
            option3: '',
            option4: ''
          }, // 添加表单的验证规则对象
          addFormRules: {
            username: [
              { require: true, message: '请输入用户名', trigger: 'blur' },
              { min: 3, max: 10, message: '用户名的长度在3~10个字符之间', trigger: 'blur' }
            ],
            id: [
              { require: true, message: '请输入账号', trigger: 'blur' },
              { min: 3, max: 10, message: '用户账号的长度在3~10个字符之间', trigger: 'blur' }
            ],
            password: [
              { require: true, message: '请输入密码', trigger: 'blur' },
              { min: 6, max: 15, message: '密码的长度在6~15个字符之间', trigger: 'blur' }
            ]
          },
            // 商品列表
            goodsList: [{
              qid: '20209888',
              uid: '42568',
              title: '什么是快乐星球',
              type: 'selection',
              answ: 'A',
              option1: 'Earth',
              option2: 'Mars',
              option3: 'Pluto',
              option4: 'Moon'
            },
              {
                qid: '20209888',
                uid: '42568',
                title: '琅琊榜中谁的武功最厉害',
                type: 'selection',
                answ: 'B',
                option1: '谢玉',
                option2: '蒙挚',
                option3: '飞流',
                option4: '靖王'
              },
              {
                qid: '20209888',
                uid: '42568',
                title: '甄嬛传中齐二哈的名句是哪个',
                type: 'selection',
                answ: 'C',
                option1: '宝嗓我的鹃子',
                option2: '皇后杀了皇后',
                option3: '翠果打烂她的嘴',
                option4: '宛宛类卿'
              },
              {
                qid: '20209888',
                uid: '42568',
                title: '武林外传里钱掌柜第一次见到的月饼是？',
                type: 'description',
                answ: '红点馒头',
                option1: '',
                option2: '',
                option3: '',
                option4: ''
              }],
            // 总的数据条数
            total: 0,
          // 控制添加用户对话框的显示和隐藏
          addDialogVisible: false,
          showQuestionList: [],
          importDialogVisible: false,
          // 批量导入对话框
          fileList: [{ name: 'excelupload1.xlsx', url: 'D:\\excelupload1.xlsx' }],
          num: [''] // 点击的折叠面板序号的列表
        }
    },
    created () {
        this.getGoodsList()
    },
    methods: {
      // 点击按钮，添加新用户
      addQues () {
        this.$refs.addFormRef.validate(async valid => {
          if (!valid) {
            return
          }
          // 发起一个添加用户的http请求
          // const {data:res} = await this.$http.post('users',this.addForm.id);
          // if(res.meta.status !== 201){
          //     this.$message.error('添加用户失败')
          // }
          this.$message.success('添加问题成功')

          // 隐藏对话框
          this.addDialogVisible = false
          // 表格增加一行
          this.goodsList.push({
            qid: Math.floor(Math.random() * 10000),
            uid: Math.floor(Math.random() * 10000),
            title: this.addForm.title,
            type: this.value,
            answ: '',
            option1: this.addForm.option1.trim(),
            option2: this.addForm.option2.trim(),
            option3: this.addForm.option3.trim(),
            option4: this.addForm.option4.trim()
          })
        })
        this.getGoodsList()
      },
      addDialogClosed () {
        this.$refs.addFormRef.resetFields()
      },
      handleChange (val) { // 折叠模板的响应函数
        console.log(val)
      },
        goAddpage () {
            this.$router.push('/questionBank/add')
        },
        async removeById (goods_id) {
            const confirmResult = await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
                }).catch(err => err)

            if (confirmResult !== 'confirm') {
                return this.$message.info('已取消删除')
            }

            // 发送http请求进行数据删除
            this.$message.success('已删除id为' + goods_id + '的数据')
        },
        handleCurrentChange (newPage) {
            this.queryInfo.pagenum = newPage
            this.getGoodsList()
        },
        handleSizeChange (newSize) {
            this.queryInfo.pagesize = newSize
            this.getGoodsList()
        },
        // 根据分页获取对应的商品列表
        async getGoodsList () {
            // 发送http请求获取数据
            // const {data,res} = await this.$http.get('questionBank',{
            //     params:this.queryInfo
            // })

            // if(this.meta.status !== 200){
            //     this.$message.error('获取商品列表失败')
            // }
          this.showQuestionList = []
          let len = this.goodsList.length
          const searchQuesList = []
          for (let i = 0; i < len; i++) {
            const ques = this.goodsList[i]
            if (this.queryInfo.query !== '') {
              if (ques.title.indexOf(this.queryInfo.query) !== -1) {
                searchQuesList.push(ques)
              }
            } else {
              searchQuesList.push(ques)
            }
          }
          // //获取对应的记录列表
          const start = (this.queryInfo.pagenum - 1) * this.queryInfo.pagesize
          len = searchQuesList.length
          for (let i = 0; i < len; i++) {
            if (i >= start && i < start + this.queryInfo.pagesize) {
              const user = searchQuesList[i]
              this.showQuestionList.push(user)
            }
          }
          this.total = searchQuesList.length
          // this.$message.success('获取商品列表成功')
        },
      // 第一步上传文件
      importExcel (file) {
        const self = this
        const types = file.name.split('.')[1]
        const fileType = ['xlsx', 'xlc', 'xlm', 'xls', 'xlt', 'xlw', 'csv'].some(
          item => item === types
        )
        console.log(fileType)
        if (!fileType) {
          alert('格式错误！请重新选择')
          return
        }
        this.file2Xce(file).then(tab => {
          // console.log(tab)
          if (tab && tab.length > 0) {
            this.tab = tab
            if (this.tab.length !== 0) {
              console.log(tab)
              this.xlscList = []
              this.tab[0].sheet.forEach(item => {
                // console.log(item.indexOf("C") != -1)
                if (item.indexOf('') !== -1) {
                  const inputInfo = item.split("'")// excel的数据类型都是text所以通过item.split("'")截取，拿到所以表的数据
                  if (inputInfo.length === 2) {
                    self.xlscList.push(inputInfo[1])
                    // console.log(self.xlscList)
                  } else {
                    const inputInfo2 = item.split('=')
                    self.xlscList.push(inputInfo2[1])
                  }
                }
              })
            }
            console.log(this.xlscList)
            console.log('1111')
            if (this.xlscList.length !== 0) {
              this.setInputToForm()
            }
          }
        })
      },
      // 对组进行切割
      setInputToForm () {
        const headerLength = 9
        if (this.xlscList.length >= headerLength) { // 判断表头的长度
          /*
          * 将一个数组分成几个同等长度的数组
          * array[分割的原数组]
          * size[每个子数组的长度]
          */
          this.xlscList = this.xlscList.slice(headerLength)
          // console.log()
          const result = []
          const personnelList = []
          for (let x = 0; x < Math.ceil(this.xlscList.length / headerLength); x++) {
            const start = x * headerLength
            const end = start + headerLength
            result.push(this.xlscList.slice(start, end))
          }
          console.log(result)
          console.log('tttt')
          // 获取每一个数组的第一个，第二个，第三个...通过push重新拼装成一个新的数组对象
          for (let i = 0; i < result.length; i++) {
            for (let j = 0; j < result[i].length; j++) {
              if (j === 0) {
                const temp = {
                  qid: result[i][j],
                  uid: result[i][j + 1],
                  title: result[i][j + 2],
                  type: result[i][j + 3],
                  answ: result[i][j + 4].trim(),
                  option1: result[i][j + 5].trim(),
                  option2: result[i][j + 6].trim(),
                  option3: result[i][j + 7].trim(),
                  option4: result[i][j + 8].trim()
                }
                console.log(temp)
                console.log('ppp')
                personnelList.push(temp)
                // personnelList.push(  { cyrjsmc: result[i][j], cyrxm: result[i][j + 1], sfzhm: result[i][j + 2],
                //   sjhm: result[i][j + 3], sfzcrmc: result[i][j + 4], sfglymc: result[i][j + 5],
                //   sfptmc: result[i][j + 5] })
              }
            }
          }
          // this.memberList = personnelList
          this.goodsList.push.apply(this.goodsList, personnelList)
          console.log('mem')
          // console.log(this.memberList)
          this.handleCurrentChange(1)
          this.importDialogVisible = false
          this.setInGlobal()
        } else {
          this.$message({
            message: '上传格式不對',
            type: 'warning'
          })
        }
      },
      setInGlobal () {
        this.Global.globalQuesBank = this.goodsList
      },
      file2Xce (file) {
        return new Promise(function (resolve, reject) {
          const reader = new FileReader()
          reader.onload = function (e) {
            const data = e.target.result
            this.wb = XLSX.read(data, {
              type: 'binary'
            })
            const result = []
            this.wb.SheetNames.forEach(sheetName => {
              result.push({
                sheetName: sheetName,
                sheet: XLSX.utils.sheet_to_formulae(this.wb.Sheets[sheetName])
              })
            })
            resolve(result)
          }
          reader.readAsBinaryString(file.raw)
        })
      }

      // 批量导入
      // importData(file, fileList) {
      //   // 拿取文件对象
      //   const f = file.raw
      //   // 用 FileReader 来读取
      //   let reader = new FileReader()
      //   // 重写 FileReader 上的 readAsBinaryString 方法
      //   FileReader.prototype.readAsBinaryString = f => {
      //     let binary = ''
      //     let wb // 读取完成的数据
      //     let outdata // 你需要的数据
      //     let reader = new FileReader()
      //     reader.onload = e => {
      //       // 读取成Uint8Array，再转换为Unicode编码（Unicode占两个字节）
      //       const bytes = new Uint8Array(reader.result)
      //       const length = bytes.byteLength
      //       for (let i = 0; i < length; i++) {
      //         binary += String.fromCharCode(bytes[i])
      //       }
      //       // 接下来就是xlsx了，具体可看api
      //       wb = XLSX.read(binary, {
      //         type: 'binary',
      //         cellDates: false
      //       })
      //       outdata = XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]])
      //       const result = this.generateParam(outdata)
      //       console.log('result--', result)
      //
      //       // 下面就进行接口调用了...
      //     }
      //     reader.readAsArrayBuffer(f)
      //   }
      //   reader.readAsBinaryString(f)
      // },
      // // 生成导入参数
      // generateParam(data) {
      //   // const params = []
      //   // 这里根据实际表格 title 值、接口参数值，灵活变化
      //   const parse = {
      //     序号: 'index',
      //     问题id: 'qid',
      //     用户id: 'uid',
      //     标题: 'title',
      //     类型: 'type',
      //     标准答案: 'answ',
      //     选项: 'options'
      //   }
      //   data.forEach(item => {
      //     let obj = {}
      //     const keys = Object.keys(parse)
      //     const itemKeys = Object.keys(item)
      //     itemKeys.forEach(key => {
      //       const val = item[key]
      //       if (keys.includes(key)) {
      //         obj[parse[key]] = val
      //       }
      //     })
      //     this.goodsList.push(obj)
      //   })
      //   this.getGoodsList()
      //   // return params
      // }
    }
}
</script>

<style lang="less" scoped>

</style>
